package com.winit.attachment.web;

import com.winit.attachment.manager.AttachmentManager;
import com.winit.attachment.model.Attachment;
import com.winit.common.base.web.BaseController;
import com.winit.commons.util.SeqGenerate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

@Api(value = "attachment", tags = {"attachment"}, description = "attachment")
@RestController
@RequestMapping("/api/v1/attachment")
public class AttachmentController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(AttachmentController.class);


    @Value("${froala_upload_url}")
    private String froala_upload_url;
    @Value("${froala_upload_path}")
    private String froala_upload_path;

    @Autowired
    private AttachmentManager attachmentManager;

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, consumes = "multipart/form-data")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "上传文件", consumes = "multipart/form-data")
    @ResponseBody
    public Map uploadFile(@ApiParam(name = "file", allowMultiple = true) @RequestParam("file") MultipartFile file,
                          @ApiParam(name = "resourceType", value = "只能是BRD、PRD、REQ、COMMON（默认，非前者即为common)") @RequestParam("resourceType") String resourceType) throws Exception {
        return this.getRtn("0", "success!", this.attachmentManager.uploadFile(file, resourceType));
    }

    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public void downloadFile(@ApiParam(name = "attachmentId") @RequestParam("attachmentId") String attachmentId,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        Attachment attachment = this.attachmentManager.getAttachmentById(attachmentId);
        if (null == attachment) {
            throw new Exception("no attachment found");
        }
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String mimeType = URLConnection.guessContentTypeFromName(attachment.getAttachmentName());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", new String(("attachment;fileName=" + attachment.getAttachmentName()).getBytes("UTF-8"), "ISO-8859-1"));
        try {
            File file = new File(attachment.getAttachmentPath(), attachment.getAttachmentId());
            if (!file.exists()) {
                throw new Exception("no file on disk found for this attachment");
            }
            long length = file.length();
            response.setContentLength((int) length);
            InputStream inputStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = inputStream.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.close();
            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }

//    @RequestMapping(value = "/froalaUpload", method = RequestMethod.POST)
//    @ResponseStatus(HttpStatus.OK)
//    @ApiOperation(value = "富文本框上传文件")
//    @ResponseBody
//    public Map froalaUpload(@ApiParam(name = "file", allowMultiple = true) @RequestParam("file") MultipartFile file) throws Exception {
//        String fileName = SeqGenerate.createId("F") + file.getOriginalFilename();
//        String basePath = froala_upload_path;
//        File directory = new File(basePath);
//        if (!directory.exists()) {
//            directory.mkdirs();
//        }
//        File targetFile = new File(directory, fileName);
//        if (!targetFile.exists()) {
//            try {
//                targetFile.createNewFile();
//            } catch (IOException e) {
//                log.error(e.getMessage(), e);
//                throw e;
//            }
//        }
//        try {
//            file.transferTo(targetFile);
//        } catch (IOException e) {
//            log.error(e.getMessage(), e);
//            throw e;
//        }
//        Map<String, String> map = new HashMap<>();
//        map.put("link", froala_upload_url + "/" + fileName);
//        return map;
//    }
}
